package com.janetfilter.core;

import com.janetfilter.core.plugin.PluginManager;

import java.lang.instrument.Instrumentation;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Initializer {
    private static final Logger logger = Logger.getLogger(Initializer.class.getName());

    public static void init(Environment environment) {
        logger.info(String.format("running Initializer.init %s", environment));

        Dispatcher dispatcher = new Dispatcher(environment);
        new PluginManager(dispatcher, environment).loadPlugins();

        Instrumentation inst = environment.getInstrumentation();
        inst.addTransformer(dispatcher, true);

        logger.info(String.format("Instrumentation isNativeMethodPrefixSupported %s", inst.isNativeMethodPrefixSupported()));
        if (inst.isNativeMethodPrefixSupported()) {
            inst.setNativeMethodPrefix(dispatcher, environment.getNativePrefix());
        }

        Set<String> classSet = dispatcher.getHookClassNames();
        for (Class<?> c : inst.getAllLoadedClasses()) {
            String name = c.getName();
            if (!classSet.contains(name)) {
                continue;
            }

            try {
                c.getGenericSuperclass();
                inst.retransformClasses(c);
            } catch (Throwable e) {
                logger.log(Level.WARNING, String.format("Retransform class failed: %s", name), e);
            }
        }
    }
}
